package com.dhcy.mqtt.config;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dhcy.mqtt.exception.GlobalException;
import com.dhcy.mqtt.exception.WxerrorExecption;
import com.dhcy.mqtt.util.AppResultData;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public AppResultData<String> globalError(HttpServletRequest req, Exception e) {
        if (e instanceof GlobalException) {
            GlobalException globalException = (GlobalException) e;
            return globalException.getAppResultData();
        } else if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            List<ObjectError> errors = bindException.getAllErrors();
            ObjectError objectError = errors.get(0);
            return AppResultData.error(objectError.getDefaultMessage(), "");

        } else if (e instanceof AuthenticationException) {
            return AppResultData.error("用户名或者密码错误", e.toString());
        } else {
            e.printStackTrace();

            return AppResultData.error("系统错误", e.toString());
        }

    }
}
